import Vue from 'vue'
import Router from 'vue-router'
import * as util from '@/assets/js/util'

Vue.use(Router)

const routes = [
  {
    name: 'Login',
    path: '/',
    component: () => import('@/views/Login.vue'),
  },
  {
    path: '/main',
    component: () => import('@/views/Main.vue'),
    children: [
      {
        name: 'Home',
        path: '',
        component: () => import('@/views/home/Index.vue')
      },
      {
        name: 'UserIndex',
        path: 'user',
        component: () => import('@/views/user/Index.vue')
      },
      {
        name: 'UserList',
        path: 'userList',
        component: () => import('@/views/user/List.vue')
      },
      {
        name: 'CourseAll',
        path: 'course',
        component: () => import('@/views/course/All.vue')
      },
      {
        name: 'CoursePrimary',
        path: 'course/primary',
        component: () => import('@/views/course/Primary.vue')
      },
      {
        name: 'CourseMiddle',
        path: 'course/middle',
        component: () => import('@/views/course/Middle.vue')
      },
      {
        name: 'CourseHigh',
        path: 'course/high',
        component: () => import('@/views/course/High.vue')
      },
      {
        name: 'Grade',
        path: 'grade',
        component: () => import('@/views/grade/Index.vue')
      },
      {
        name: 'Education',
        path: 'education',
        component: () => import('@/views/education/Index.vue')
      },
      {
        name: 'Student',
        path: 'manage/student',
        component: () => import('@/views/manage/Student.vue')
      },
      {
        name: 'Teacher',
        path: 'manage/teacher',
        component: () => import('@/views/manage/Teacher.vue')
      },
      {
        name: 'School',
        path: 'manage/school',
        component: () => import('@/views/manage/School.vue')
      }
    ]
  }
]

const router = new Router({
  routes,
  scrollBehavior(to, from, savePosition) {
    if (savePosition) {
      return savePosition
    } else {
      return {
        x: 0,
        y: 0
      }
    }
  }
})

router.beforeEach((to, from, next) => {
  const loginStatus = util.localStorage.get('login')
  const { name } = to
  if (name === 'Login') {
    loginStatus ? next('/main') : next()
  } else {
    loginStatus ? next() : next('/')
  }
})

export default router
